package marvin.webapp.shopping.action;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import marvin.webapp.common.action.AbstractWebAction;
import marvin.webapp.common.util.WebPageURLs;
import marvin.webapp.exception.MarvinException;
import marvin.webapp.shopping.displaybeans.ShoppingListDisplayBean;
import marvin.webapp.shopping.model.Item;
import marvin.webapp.shopping.model.ShoppingList;
import marvin.webapp.shopping.model.ShoppingListComparator;
import marvin.webapp.shopping.xml.ShoppingListXMLParser;
import marvin.webapp.shopping.xml.ShoppingListXMLWriter;

@ManagedBean
@ViewScoped
public class ShoppingListsAction extends AbstractWebAction {

	private static final long serialVersionUID = -5795239982588156822L;
	public static final String SHOPPING_LIST_DB_KEY = ShoppingList.class
			.getSimpleName();

	private List<ShoppingListDisplayBean> allLists;
	private ShoppingListDisplayBean selectedShoppingList;
	private String shoppingFolderPath;

	private boolean detailsDialogVisible = false;
	private boolean editionDialogVisible = false;
	private boolean creationDialogVisible = false;

	private ShoppingList newList;
	private Item selectedItem;

	@PostConstruct
	public void load() {
		shoppingFolderPath = FacesContext.getCurrentInstance()
				.getExternalContext().getRealPath("temp/shopping");

		String listName = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap()
				.get(SHOPPING_LIST_DB_KEY);
		if (listName != null) {
			try {
				selectedShoppingList = new ShoppingListDisplayBean(
						ShoppingListXMLParser.parse(new File(shoppingFolderPath
								+ File.separator + listName + ".xml")));
			} catch (MarvinException e) {
				e.printStackTrace();
			}
		}
		File folder = new File(shoppingFolderPath);
		if (!folder.exists())
			folder.mkdirs();
		readStoredList();
	}

	private void readStoredList() {
		allLists = new LinkedList<ShoppingListDisplayBean>();
		File folder = new File(shoppingFolderPath);
		if (folder.exists()) {
			for (File child : folder.listFiles()) {

				if (child.isFile() && child.getName().endsWith(".xml")) {
					try {
						// load existing list
						allLists.add(new ShoppingListDisplayBean(
								ShoppingListXMLParser.parse(child)));
					} catch (MarvinException e) {
						e.printStackTrace();
					}
				}
			}
			
			Collections.sort(allLists, new ShoppingListComparator());
		}
	}

	public void deleteSelectedList(){
		if(selectedShoppingList != null){
			try{
				File file = new File(shoppingFolderPath + File.separator
									+ selectedShoppingList.getList().getCreationDate() + ".xml");
				if(file.exists())
					file.delete();
				
				readStoredList();
			} catch (Exception e) {
				displayMessage(FacesMessage.SEVERITY_ERROR,
						"Shopping list deletion", e.getMessage());
			}
		}
	}
	
	public void copySelectedList(){
		if(selectedShoppingList != null){
			ShoppingListXMLWriter wr = new ShoppingListXMLWriter();
			ShoppingList copy = new ShoppingList();
			for (Item item : selectedShoppingList.getList().getItems()) {
				copy.addItem(item);
			}
			
			try {
				wr.generate(
						copy,
						shoppingFolderPath + File.separator
								+ copy.getCreationDate() + ".xml");
				readStoredList();
			} catch (MarvinException e) {
				displayMessage(FacesMessage.SEVERITY_ERROR,
						"Shopping list copy", e.getMessage());
			}
		}
	}
	
	public boolean isFormVisible(){
		return !(isCreationDialogVisible() || isEditionDialogVisible());
	}
	
	public void showListDetails() {
		if (isOnMobile()) {
			try {
				FacesContext
						.getCurrentInstance()
						.getExternalContext()
						.redirect(
								WebPageURLs.SHOPPING_MOBILE_DETAILS_PAGE
										+ "?"
										+ SHOPPING_LIST_DB_KEY
										+ "="
										+ selectedShoppingList.getList()
												.getCreationDate());
			} catch (IOException e) {
				displayMessage(FacesMessage.SEVERITY_ERROR,
						"Show list details", e.getMessage());
			}
		} else {
			setDetailsDialogVisible(true);
		}
	}

	public void hideListDetails() {
		setDetailsDialogVisible(false);
	}

	public void showListCreationDialog() {
		newList = new ShoppingList();
		setCreationDialogVisible(true);
	}

	public void addItemInNewList() {
		if(newList != null)
			newList.addItem(new Item());
	}
	
	public void removeItemInNewList() {
		if (newList != null && selectedItem != null)
			newList.removeItem(selectedItem);
	}

	public void cancelNewListCreation() {
		setCreationDialogVisible(false);
	}

	public void createNewList() {
		ShoppingListXMLWriter wr = new ShoppingListXMLWriter();
		try {
			wr.generate(
					newList,
					shoppingFolderPath + File.separator
							+ newList.getCreationDate() + ".xml");
			readStoredList();
			cancelNewListCreation();
		} catch (MarvinException e) {
			displayMessage(FacesMessage.SEVERITY_ERROR,
					"Shopping list creation", e.getMessage());
		}
	}

	public void tickItem() {
		if (selectedItem != null) {
			selectedItem.setTicked(!selectedItem.isTicked());
			updateSelectedList();
		}
	}

	public void updateSelectedList() {
		ShoppingListXMLWriter wr = new ShoppingListXMLWriter();
		try {
			wr.generate(selectedShoppingList.getList(), shoppingFolderPath + File.separator
					+ selectedShoppingList.getList().getCreationDate() + ".xml");
			hideEditionDialog();
		} catch (MarvinException e) {
			displayMessage(FacesMessage.SEVERITY_ERROR,
					"Shopping list creation", e.getMessage());
		}
	}

	public void addItemInEditedList() {
		if (selectedShoppingList != null)
			selectedShoppingList.getList().addItem(new Item());
	}

	public void removeItemInEditedList() {
		if (selectedShoppingList != null && selectedItem != null)
			selectedShoppingList.getList().removeItem(selectedItem);
	}
	
	

	public void hideEditionDialog() {
		readStoredList();
		setEditionDialogVisible(false);
	}

	public void showEditionDialog() {
		setEditionDialogVisible(true);
	}

	public List<ShoppingListDisplayBean> getAllLists() {
		return allLists;
	}

	public void setSelectedShoppingList(
			ShoppingListDisplayBean selectedShoopingList) {
		this.selectedShoppingList = selectedShoopingList;
	}

	public ShoppingListDisplayBean getSelectedShoppingList() {
		return selectedShoppingList;
	}

	public void setDetailsDialogVisible(boolean detailsDialogVisible) {
		this.detailsDialogVisible = detailsDialogVisible;
	}

	public boolean isDetailsDialogVisible() {
		return detailsDialogVisible;
	}

	public void setCreationDialogVisible(boolean creationDialogVisible) {
		this.creationDialogVisible = creationDialogVisible;
	}

	public boolean isCreationDialogVisible() {
		return creationDialogVisible;
	}

	public ShoppingList getNewList() {
		return newList;
	}

	public void setSelectedItem(Item selectedItem) {
		this.selectedItem = selectedItem;
	}

	public Item getSelectedItem() {
		return selectedItem;
	}

	public void setEditionDialogVisible(boolean editionDialogVisible) {
		this.editionDialogVisible = editionDialogVisible;
	}

	public boolean isEditionDialogVisible() {
		return editionDialogVisible;
	}
}
